﻿// For an introduction to the Search Contract template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232512

// TODO: Add the following script tag to the start page's head to
// subscribe to search contract events.
//  
// <script src="/searchResultPage.js"></script>

(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var appModel = Windows.ApplicationModel;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var utils = WinJS.Utilities;
    var searchPageURI = "/pages/searchResultPage/searchResultPage.html";

    ui.Pages.define(searchPageURI, {
        _filters: [],
        _lastSearch: "",

        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var listView = element.querySelector(".resultslist").winControl;
            listView.itemTemplate = element.querySelector(".itemtemplate");
            listView.oniteminvoked = this._itemInvoked;
            //this._handleQuery(element, options);
            //listView.element.focus();
            listView.addEventListener("keydown", function (e) {
                if (Windows.UI.ViewManagement.ApplicationView.value !== appViewState.snapped && e.ctrlKey && e.keyCode === WinJS.Utilities.Key.g && e.altKey) {
                    var data = listView.itemDataSource.list.getAt(listView.currentItem.index);
                    this.navigateToGroup(data.group.key);
                    e.preventDefault();
                    e.stopImmediatePropagation();
                }
            }.bind(this), true);
            document.querySelector(".titlearea .pagetitle").textContent = "Search Results " + "for '" + options.queryText + "'";
            this._initializeLayout(element.querySelector(".resultslist").winControl, Windows.UI.ViewManagement.ApplicationView.value);
            listView.element.focus();

        },

        // This function updates the page layout in response to viewState changes.
        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            var listView = element.querySelector(".resultslist").winControl;
            if (lastViewState !== viewState) {
                if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
                    var handler = function (e) {
                        listView.removeEventListener("contentanimating", handler, false);
                        e.preventDefault();
                    }
                    listView.addEventListener("contentanimating", handler, false);
                    var firstVisible = listView.indexOfFirstVisible;
                    this._initializeLayout(listView, viewState);
                    if (firstVisible >= 0 && listView.itemDataSource.list.length > 0) {
                        listView.indexOfFirstVisible = firstVisible;
                    }
                }
            }
        },

   

        // This function updates the ListView with new layouts
        _initializeLayout: function (listView, viewState) {
            /// <param name="listView" value="WinJS.UI.ListView.prototype" />

            if (viewState === appViewState.snapped) {
                listView.itemDataSource = Data.items.dataSource;
                listView.groupDataSource = null;
                listView.layout = new ui.ListLayout();
                //document.querySelector(".titlearea .pagetitle").textContent = '“' + this._lastSearch + '”';
                document.querySelector(".titlearea .pagesubtitle").textContent = "";
            } else {
                listView.itemDataSource =Data.items.dataSource;
                listView.layout = new ui.GridLayout();

                // TODO: Change "App Name" to the name of your app.
                //document.querySelector(".titlearea .pagetitle").textContent = "App Name";
                //document.querySelector(".titlearea .pagesubtitle").textContent = "Results for “" + this._lastSearch + '”';
            }
        },

        _itemInvoked: function (args) {
            args.detail.itemPromise.done(function itemInvoked(item) {
                // TODO: Navigate to the item that was invoked.
                if (Windows.UI.ViewManagement.ApplicationView.value === appViewState.snapped) {
                    // If the page is snapped, the user invoked a group.
                    //var group = HubData.groups.getAt(args.detail.itemIndex);
                    //this.navigateToGroup(group.key);
                    var item = Data.items.getAt(args.detail.itemIndex);
                    nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
                } else {
                    // If the page is not snapped, the user invoked an item.
                    var item = Data.items.getAt(args.detail.itemIndex);
                    if (item == null) {
                        var item1 = Data.items.getAt(0);
                        nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item1) });
                    } else {
                        nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
                    }
                }
            });
        },

        // This function colors the search term. Referenced in /searchResultPage.html
        // as part of the ListView item templates.
      

        // This function generates the filter selection list.
       

        // This function populates a WinJS.Binding.List with search results for the
        // provided query.
      
    });

    WinJS.Application.addEventListener("activated", function (args) {
        if (args.detail.kind === appModel.Activation.ActivationKind.search) {
            args.setPromise(ui.processAll().then(function () {
                if (!nav.location) {
                    nav.history.current = { location: Application.navigator.home, initialState: {} };
                }

                return nav.navigate(searchPageURI, { queryText: args.detail.queryText });
            }));
        }
    });

    appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args) { nav.navigate(searchPageURI, args); };
    appModel.Search.SearchPane.getForCurrentView().onresultsuggestionchosen = function (eventObject) { onResultSuggestionChosen(item, eventObject); };

})();
